module.exports = function ($scope, $resource, $modalInstance, type, toaster) {

    $scope.type = type;
    $scope.tempObj = {};
    $scope.goodsCodeArr = [];
    $scope.goodsCodeMap = [];
    $scope.dataMap = {};
    $resource('/api/ac/vc/viewGoodsService/pcListNoPage', {}, {}).save({}, function (res) {
        if (res.errcode === 0) {
            $scope.goodsList = res.data;
            for (var index = 0; index < $scope.goodsList.length; index++) {
                var element = $scope.goodsList[index];
                $scope.dataMap[element.code] = element;
            }
            var codeList = $scope.type.goods_code.split(',');
            for (var i = 0; i < codeList.length; i++) {
                var element = codeList[i];
                $scope.goodsCodeArr.push(angular.copy($scope.dataMap[element]));
                $scope.goodsCodeMap[element] = true;
            }
        } else {
            toaster.error({ title: '', body: res.errmsg });
        }
    });

    $scope.add = function(){
        if (!$scope.tempObj.goods) {
            toaster.warning({title: "", body: "请选择一个产品"});
            return false;
        }
        if ($scope.goodsCodeMap[$scope.tempObj.goods.code]) {
            toaster.warning({title: "", body: "请不要选择重复产品"});
            return false;
        }
        $scope.goodsCodeArr.push(angular.copy($scope.tempObj.goods));
        $scope.goodsCodeMap[$scope.tempObj.goods.code] = true;
    }

    $scope.remove = function(index){
        delete $scope.goodsCodeMap[$scope.goodsCodeArr[index]];
        $scope.goodsCodeArr.splice(index, 1);
    }

    //添加一卡通
    $scope.ok = function () {
        if ($scope.goodsCodeArr.length < 1) {
            toaster.error({ title: '', body: '请至少选择一个产品' });
            return false;
        }
        var para = {};
        var goodsCodeArray = [];
        for (var index = 0; index < $scope.goodsCodeArr.length; index++) {
            var element = $scope.goodsCodeArr[index];
            goodsCodeArray[index] = element.code;
        }
        para = {
            list: goodsCodeArray,
            type_code: $scope.type.code
        }
        para.list = goodsCodeArray;
        $resource('/api/ac/vc/viewGoodsService/updateTypeGoods', {}, {}).save(para, function (res) {
            if (res.errcode === 0) {
                $modalInstance.close();
            } else {
                toaster.error({ title: '', body: res.errmsg });
            }
        });
    }

    //取消
    $scope.close = function () {
        $modalInstance.dismiss('cancel');
    }

};